package com.dwd.user.intercepter;

import com.dwd.org.service.IEmployeeService;
import com.dwd.user.pojo.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author 汶狄
 * @Date 2021/1/18 18:44
 * @Version 1.0
 */
@Component
public class LoginInfoIntercepter implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IEmployeeService employeeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        //从请求头获取token
        String token = request.getHeader("token");
        //获取用户
        LoginInfo loginInfo =null;
        if (StringUtils.isEmpty(token)) {
            //响应状态为flase 和nologin
            response.setContentType("text/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        } else {
             loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
            //如果redis没有该值，说明过期了
            if (StringUtils.isEmpty(loginInfo)) {
                //响应状态为flase 和nologin
                response.setContentType("text/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                //手动返回json
                writer.write("{\"success\":false,\"message\":\"noLogin\"}");
                return false;
            }
            //重新给他设置30分钟
            redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        }
        //获取所有权限
        List<String> permis = employeeService.queryAllPermis();
        //当前请求
        String url = request.getRequestURI();
        if (permis.contains(url)) {
            //包含
            //根据登陆用户的id查询员工id
            Long id = employeeService.queryempIdByLoginInfoId(loginInfo.getId());
            //获取当前人的权限
            List<String> empPermis = employeeService.queryPermis(id);
            if (empPermis.contains(url)) {
                //有权限
                return true;
            } else {
                //没有权限。拦截,跳转
                //响应状态为flase 和nologin
                response.setContentType("text/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                //手动返回json
                writer.write("{\"success\":false,\"message\":\"nopermission\"}");
                return false;
            }
        }
        return true;
    }
}
